<template>
  <div class="dashboard-container">
    <!-- 经营概况和时间选择 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card shadow="hover" class="dashboard-card">
          <div class="time-range">
            <span class="section-title">经营概况</span>
            <div class="time-selectors">
              <el-select v-model="selectedValue" filterable remote reserve-keyword placeholder="全部" :loading="loading" @change="handleSelectChange">
                <el-option label="今天" value="today" />
                <el-option label="昨天" value="yesterday" />
                <el-option label="7日" value="7days" />
                <el-option label="30日" value="30days" />
              </el-select>
              <el-date-picker
                v-model="dateRange"
                type="datetimerange"
                value-format="YYYY-MM-DD HH:mm:ss"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="handleDateRangeChange"
              />
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 实时数据区块 -->
    <el-row :gutter="20">
      <!-- 用户数据 -->
      <el-col :span="12">
        <el-card shadow="hover" class="dashboard-card">
          <div class="data-section">
            <div class="section-header">
              <el-icon><User /></el-icon>
              <span class="section-title">用户数据</span>
            </div>
            <el-row :gutter="16">
              <el-col :span="8" v-for="(item, index) in userStats" :key="index">
                <div class="data-item">
                  <div class="data-label">{{ item.label }}</div>
                  <div class="data-value" @click="handleOrderClick">
                    {{ item.unit }} {{ item.isCurrency ? formatCurrency(item.value) : item.value }}
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>

      <!-- 茶空间数据 -->
      <el-col :span="12">
        <el-card shadow="hover" class="dashboard-card">
          <div class="data-section">
            <div class="section-header">
              <el-icon><OfficeBuilding /></el-icon>
              <span class="section-title">茶空间数据</span>
            </div>
            <el-row :gutter="16">
              <el-col :span="8" v-for="(item, index) in roomStats" :key="index">
                <div class="data-item">
                  <div class="data-label">{{ item.label }}</div>
                  <div class="data-value">{{ item.unit }} {{ item.isCurrency ? formatCurrency(item.value) : item.value }}</div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 团购数据 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card shadow="hover" class="dashboard-card">
          <div class="data-section">
            <div class="section-header">
              <el-icon><TrendCharts /></el-icon>
              <span class="section-title">团购数据</span>
            </div>

            <el-row :gutter="24" class="platform-row">
              <!-- 美団平台 -->
              <el-col :span="8" v-for="(item, index) in groupBuyTotal" :key="index">
                <div class="platform-card" :class="`platform-${getPlatformClass(item.plateType)}`">
                  <div class="platform-header">
                    <svg-icon :icon-class="getPlatformIcon(item.plateType)" />
                    <span class="platform-name">{{ getPlatformName(item.plateType) }}数据</span>
                  </div>
                  <el-row :gutter="12">
                    <el-col :span="12">
                      <div class="data-item">
                        <div class="data-label">
                          <el-icon><Money /></el-icon>收入
                        </div>
                        <div class="data-value">¥ {{ floatToFixed2(item.originalAmount) }}</div>
                      </div>
                    </el-col>
                    <el-col :span="12">
                      <div class="data-item">
                        <div class="data-label">
                          <el-icon><Checked /></el-icon>核销数量
                        </div>
                        <div class="data-value">{{ item.useNum }}</div>
                      </div>
                    </el-col>
                  </el-row>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="24">
        <el-card shadow="hover" class="dashboard-card">
          <div class="data-section">
            <div class="section-header">
              <el-icon><TrendCharts /></el-icon>
              <span class="section-title">订单统计</span>
            </div>
          </div>
          <div ref="chartContainer" class="order-chart"></div>
        </el-card>
      </el-col>    
    </el-row>
  </div>
</template>

<script setup name="queryCount" lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';
import { floatToFixed2 } from '@/utils/index';
import { getUserCountInfo, getOrderCountInfo, getGroupBuyTotal, getRoomTotal, getBalances, getRefundInfo, getOrderTotalStats, getBalancePay} from '@/api/tearoom/queryCount/index';
import { TerOrderDayVo, TerUserDayVo, StatItem, TerGroupBuyTotalVo } from '@/api/tearoom/queryCount/types';
import { AccountsForm } from '@/api/tearoom/accounts/types';
import dayjs from 'dayjs';
// 响应式数据
const router = useRouter();
const userTotal = ref<TerUserDayVo>();
const orderTotal = ref<TerOrderDayVo>();
const refundTotal = ref<TerOrderDayVo>();
const wxPayTotal = ref<TerOrderDayVo>();
const banlancePay = ref<TerOrderDayVo>();
const groupBuyTotal = ref<TerGroupBuyTotalVo>();
const selectedValue = ref('today');
const loading = ref(false);
const getUserTotal = async (params: { daynum?: number; start?: string; end?: string }) => {
  const res = await getUserCountInfo(params);
  return res.data;
};

const getOrderTotal = async (params: { daynum?: number; start?: string; end?: string }) => {
  const res = await getOrderCountInfo(params);
  return res.data;
};
const getRefundTotal = async (params: { daynum?: number; start?: string; end?: string }) => {
  const res = await getRefundInfo(params);
  return res.data;
};
const getGroupBuyTotalData = async (dateRange?: any) => {
  const [startTime, expireTime] = dateRange.value;
  const params = {
    startTime: startTime,
    expireTime: expireTime
  };
  const res = await getGroupBuyTotal(params);
  return res.data;
};

const getOrderTotalStatsData = async (dateRange?: any) => {
  // console.log(dateRange);
  // const params = {
  //   start: dateRange.value[0],
  //   end: dateRange.value.end[1]
  // };
  const res = await getOrderTotalStats(dateRange);
  return res.data;
};

const dateRange = ref<[Date, Date] | null>(null);

const PLATFORM_CONFIG = {
  2: {
    css: 'mt',
    icon: 'meituan',
    name: '美团'
  },
  3: {
    css: 'dy',
    icon: 'douyin',
    name: '抖音'
  },
  4: {
    css: 'ks',
    icon: 'kuaishou',
    name: '快手'
  }
};

const getPlatformClass = (type?: number) => {
  return PLATFORM_CONFIG[type]?.css || '';
};
const getPlatformIcon = (type?: number) => {
  return PLATFORM_CONFIG[type]?.icon || '';
};
const getPlatformName = (type?: number) => {
  return PLATFORM_CONFIG[type]?.name || '未知平台';
};

const userStats = ref<StatItem[]>([
  { label: '在线数', value: 0, unit: '' },
  { label: '注册数', value: 0, unit: '' },
  { label: '订单数量', value: 0, unit: '' },
  { label: '余额充值', value: 0, unit: '' },
  { label: '会员卡充值(元)', value: 0, unit: '', isCurrency: true }
]);

const roomStats = ref<StatItem[]>([
  { label: '总收入(元)', value: 0, unit: '', isCurrency: true },
  { label: '微信支付(元)', value: 0, unit: '', isCurrency: true },
  { label: '退款金额(元)', value: 0, unit: '', isCurrency: true },
  { label: '太空舱数量', value: 7, unit: '' }
]);

const timeMap = {
  today: 0,
  yesterday: 1,
  '7days': 7,
  '30days': 30
};
// 订单点击事件
const handleOrderClick = () => {
  const timeFormat = 'YYYY-MM-DD HH:mm:ss';
  let params = { start: '', end: '' };

  switch (selectedValue.value) {
    case 'today': // 当天完整时间范围
      params.start = dayjs().startOf('day').format(timeFormat); // 00:00:00
      params.end = dayjs().endOf('day').format(timeFormat); // 23:59:59
      break;
    case 'yesterday':
      params.start = dayjs().subtract(1, 'day').startOf('day').format(timeFormat);
      params.end = dayjs().subtract(1, 'day').endOf('day').format(timeFormat);
      break;
    case '7days':
      params.start = dayjs().subtract(6, 'day').startOf('day').format(timeFormat);
      params.end = dayjs().endOf('day').format(timeFormat);
      break;
    case '30days':
      params.start = dayjs().subtract(29, 'day').startOf('day').format(timeFormat);
      params.end = dayjs().endOf('day').format(timeFormat);
      break;
    default:
      if (dateRange.value && dateRange.value.length === 2) {
        params.start = dayjs(dateRange.value[0]).format(timeFormat); // 正确获取开始时间
        params.end = dayjs(dateRange.value[1]).format(timeFormat); // 正确获取结束时间
      }
      break;
  }

  // 跳转到订单页并携带参数
  router.push({
    path: '/order/orderDetails',
    query: {
      startTime: params.start,
      endTime: params.end
    }
  });
};
const formatCurrency = (value: number | undefined) => {
  // 处理空值和非法值
  const validValue = Number(value) || 0;
  return new Intl.NumberFormat('zh-CN', {
    style: 'decimal',
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  }).format(validValue);
};
// function handleApiResponse<T>(response: AxiosResponse<ApiResponse<T>>): T {
//   const res = response.data;
//   return res;
// }
// 统一获取数据的方法
const fetchData = async () => {
  try {
    loading.value = true;
    const timeFormat = 'YYYY-MM-DD HH:mm:ss';
    let params: { daynum?: number; start?: any; end?: any } = {};
    switch (selectedValue.value) {
      case 'today': // 当天完整时间范围
        params.start = dayjs().startOf('day').format(timeFormat); // 00:00:00
        params.end = dayjs().endOf('day').format(timeFormat); // 23:59:59
        break;
      case 'yesterday':
        params.start = dayjs().subtract(1, 'day').startOf('day').format(timeFormat);
        params.end = dayjs().subtract(1, 'day').endOf('day').format(timeFormat);
        break;
      case '7days':
        params.start = dayjs().subtract(6, 'day').startOf('day').format(timeFormat);
        params.end = dayjs().endOf('day').format(timeFormat);
        break;
      case '30days':
        params.start = dayjs().subtract(29, 'day').startOf('day').format(timeFormat);
        params.end = dayjs().endOf('day').format(timeFormat);
        break;
      default:
        if (dateRange.value && dateRange.value.length === 2) {
          params.start = dayjs(dateRange.value[0]).format(timeFormat); // 正确获取开始时间
          params.end = dayjs(dateRange.value[1]).format(timeFormat); // 正确获取结束时间
        }
        break;
    }
    dateRange.value = [params.start, params.end];

    // 处理日期范围参数
    if (dateRange.value && dateRange.value.length === 2) {
      const [start, end] = dateRange.value;
      params = {
        start: dayjs(start).format('YYYY-MM-DD'),
        end: dayjs(end).format('YYYY-MM-DD')
      };
    } else if (selectedValue.value) {
      params.daynum = timeMap[selectedValue.value as keyof typeof timeMap];
    }
    const balancParams = { ...params, payMethod: '钱包' };
    const wxParams = { ...params, payMethod: '微信' };
    // 保持原有数据获取逻辑
    const [userData, orderData, groupBuyData, totalnum, amount, refund, banlancePayData, wxPayData, orderStats] = await Promise.all([
      getUserTotal(params),
      getOrderTotal(params),
      getGroupBuyTotalData(dateRange),
      getRoomTotal(),
      getBalances(params),
      getRefundTotal(params),
      getBalancePay(balancParams),
      getBalancePay(wxParams),
      getOrderTotalStatsData(params)
    ]);
    // 更新 ref 对象
    userTotal.value = userData;
    refundTotal.value = refund;
    orderTotal.value = orderData;
    groupBuyTotal.value = groupBuyData;
    wxPayTotal.value = wxPayData.data;
    banlancePay.value = banlancePayData.data;
    const orderAmounts = Number(orderTotal.value.dailyTotalPrice) || 0;
    const totalAmount = orderAmounts + Number(amount.data) + groupBuyTotal.value.reduce((sum, item) => sum + item.originalAmount, 0);
    userStats.value = [
      { label: '在线数', value: userTotal.value?.onlineCount || 0, unit: '' },
      { label: '注册数', value: userTotal.value?.registered || 0, unit: '' },
      { label: '订单数量', value: orderTotal.value?.dailyOrderCount || 0, unit: '' },
      { label: '会员充值', value: floatToFixed2(Number(amount.data)) || 0, unit: '¥' },
      { label: '会员卡充值(元)', value: 0, unit: '¥' }
    ];
    // 更新订单数据
    roomStats.value = [
      { label: '总收入(元)', value: floatToFixed2(totalAmount) || 0, unit: '¥' },
      { label: '微信支付(元)', value: floatToFixed2(wxPayTotal.value?.dailyTotalPrice) || 0, unit: '¥' },
      { label: '余额支付(元)', value: floatToFixed2(banlancePay.value?.dailyTotalPrice), unit: '¥' },
      { label: '退款金额(元)', value: floatToFixed2(refundTotal.value?.dailyTotalPrice), unit: '¥' },
      { label: '太空舱数量', value: totalnum.data || 0, unit: '' } // 保持静态值
    ];
    initChart(orderStats, dateRange);
    window.addEventListener('resize', handleResize);
  } catch (error) {
    console.error('数据获取失败:', error);
  } finally {
    loading.value = false;
  }
};
// 选择器变化处理
const handleSelectChange = () => {
  dateRange.value = null; // 使用null代替空字符串
  fetchData();
};

const handleDateRangeChange = () => {
  if (dateRange.value) {
    selectedValue.value = ''; // 清空预设选择
    fetchData();
  }
};

const chartContainer = ref(null);
let chartInstance = null;

// 初始化图表
const initChart = (data, dateRange) => {
  const [startTime, expireTime] = dateRange.value;
  const startDate = dayjs(startTime).format('YYYY年MM月DD日');
  const endDate = dayjs(expireTime).format('YYYY年MM月DD日');
  if (data.data.length === 0) {
    chartInstance?.showLoading({
      text: '暂无数据',
      color: '#409EFF',
      textColor: '#333'
    });
    return;
  }
  if (!chartContainer.value) return;
  const isHourly = data.timeUnit === 'HOUR';
  const option = {
    title: {
      text: isHourly ? startDate+'每小时订单数量' : startDate+'至'+endDate+'每日订单数量',
      left: 'center',
      textStyle: {
        color: '#333'
      }
    },
    toolbox: {
      feature: {
        saveAsImage: {
          title: '保存为图片',
          name: `订单统计_${dayjs(new Date().getTime()).format("YYYY年MM月DD日")}`,
          type: 'png',
          excludeComponents: ['toolbox'],
          pixelRatio: 2
        }
      },
      right: 20
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        const date = params[0].name.split(':')[0];
        const value = params[0].value;
        return `${isHourly ? '时间' : '日期'}: ${date}<br/>订单数: ${value}`;
      }
    },
    xAxis: {
      type: 'category',
      data: data.data.map(item => item.timeUnit),
      axisLabel: {
        formatter: value => isHourly ? value.split(':')[0] + '时' : value,
        color: '#666'
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: value => `${value} 单`,
        color: '#666'
      }
    },
    series: [{
      data: data.data.map(item => item.count),
      type: 'line',
      smooth: true,
      itemStyle: {
        color: '#409EFF'
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(64, 158, 255, 0.6)' },
          { offset: 1, color: 'rgba(64, 158, 255, 0.01)' }
        ])
      }
    }],
    grid: {
      left: '3%',
      right: '3%',
      bottom: '10%',
      containLabel: true
    }
  };
  if (!chartInstance) {
    chartInstance = echarts.init(chartContainer.value);
  }
  chartInstance.setOption(option);
};

// 响应式调整
const handleResize = () => {
  chartInstance?.resize();
};

onMounted(fetchData);

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);
  chartInstance?.dispose();
});
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.mb-20 {
  margin-bottom: 20px;
}

.time-range {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.time-selectors {
  display: flex;
  gap: 10px;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  margin-left: 8px;
}

.data-item {
  text-align: center;
  padding: 12px;
  background-color: #f8f9fc;
  border-radius: 4px;
  margin-bottom: 10px;
}

.data-label {
  color: #909399;
  font-size: 12px;
  margin-bottom: 8px;
}

.data-value {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.bottom-stat {
  padding: 15px;
  background-color: #f8f9fc;
  border-radius: 4px;
  text-align: center;
}

.stat-label {
  color: #909399;
  font-size: 12px;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.dashboard-card {
  border-radius: 12px;
  margin-top: 20px;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  margin-left: 8px;
}

.platform-card {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  border-left: 4px solid transparent;
}

.platform-dy {
  border-left-color: #111111;
}

.platform-ks {
  border-left-color: #ff4a08;
}

.platform-mt {
  border-left-color: #ffc300;
}

.platform-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.platform-name {
  font-size: 16px;
  font-weight: 500;
  margin-left: 8px;
}

.data-item {
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  margin-bottom: 8px;
}

.data-label {
  color: #606266;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.data-label .el-icon {
  margin-right: 6px;
}

.data-value {
  font-size: 24px;
  font-weight: 700;
  margin: 8px 0;
  color: #303133;
}

.data-trend {
  font-size: 12px;
  font-weight: 500;
}

.up {
  color: #67c23a;
}

.down {
  color: #f56c6c;
}

.order-chart {
  width: 100%;
  height: 500px; /* 可根据需要调整高度 */
}
</style>
